<template>
  <div class="relative">
    <div class="backFont"><el-button icon="el-icon-arrow-left" @click="back()">返回</el-button></div>
    <el-form
      :model="addForm"
      :rules="rules"
      ref="ruleForm"
      :label-position="'right'"
      label-width="100px"
      class="demo-ruleForm errorForm mt20"
    >
      <!-- 入库类型字典 -->
      <el-form-item class="noRequire" label="*时间：" prop="dateTime">
        <el-date-picker
          class="widthInput"
          clearable
          v-model="addForm.dateTime"
          type="daterange"
          range-separator="一"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item class="noRequire" label="*农事类型：" prop="agriCode">
        <!-- <el-select class="selectInput" ref="selectInput" @visible-change="visibleChange" v-model="addForm.agriCode" clearable placeholder="请选择农事类型">
            <el-option
              v-for="item in farmsList"
              :key="item.userId"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
        </el-select> -->
        <el-button
          class="typeBtn"
          :class="addForm.agriCode === item.code && 'checkBoxAll'"
          @click="addForm.agriCode = item.code"
          v-for="item in farmsList"
          :key="item.id"
        >
          {{ item.name }}
        </el-button>
      </el-form-item>
      <el-form-item class="noRequire" label="*操作人：" prop="userId">
        <el-select class="widthInput" clearable v-model="addForm.userId" placeholder="请选择操作人">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="noRequire" label="*地块(多选)：" prop="landName">
        <div class="landFlex">
          <div class="landContent relative" v-for="(item, index) in addForm.landList" :key="item.id">
            <div class="landContentT">
              {{ item.landName }}
              <span :class="item.state === 1 ? 'whiteGreenBtn' : 'whiteGreenBtn'">
                {{ item.state === 1 ? "种植中" : "闲置中" }}
              </span>
            </div>
            <div class="landContentC">
              <span>面积：{{ item.landArea }}亩</span>
              <span>种植物：{{ item.plantingVariety }}</span>
            </div>
            <i class="el-icon-error" @click="deleteLand(index)"></i>
          </div>
          <div class="landContentBtn">
            <el-button type="primary" class="addBtn greenBtn" @click="getAgriLand()">
              添加地块
            </el-button>
          </div>
        </div>
        <!-- <el-input readonly @click.native="getAgriLand()" suffix-icon="el-icon-arrow-right" v-model="addForm.landName" placeholder="请选择地块" /> -->
      </el-form-item>
      <el-form-item label="备注：" prop="remark">
        <el-input v-model="addForm.remark" rows="4" type="textarea" placeholder="请输入备注内容">
        </el-input>
      </el-form-item>
    </el-form>
    <!-- <div class="textCenter">
      <el-button class="greenBtn" type="primary" size="small" @click="submitForm('ruleForm')"
        >编辑</el-button
      >
    </div> -->
    <div class="submitBottom">
      <el-button
        size="small"
        class="editBtn editBtnNone"
        @click="back()"
        >取消</el-button
      >
      <el-button
        class="editBtn"
        type="primary"
        size="small"
        @click="submitForm('ruleForm')"
      >
        保存
      </el-button>
    </div>
    <agriLand ref="agriLand" @getLandIds="getLandIds"/>
  </div>
</template>

<script>
import { getUserListApi, getSysSonDictListApi, addDic } from '@/api/dict'
import { getBaseInfolistApi, addAgriplantApi, updateAgriplan, getDetailById } from '@/api/baseInfo'

import agriLand from './agriLand' // 地块管理
// import farmStockDialog from './components/farmStockDialog'
export default {
  name: 'DateTimeAdd',
  components: {
    agriLand
  },

  data () {
    return {
      baseId: 0,
      dialogVisible: false,
      dialogCustom: false,
      farmsList: [],
      formCustom: {
        name: null,
        code: null
      },
      addForm: {
        landIds: null,
        agriCode: null,
        startTime: null,
        endTime: null,
        landName: null,
        dateTime: null,
        remark: '',
        userId: null,
        landList: []
      },
      rules: {
        agriCode: [{ required: true, message: '请选择农事类型', trigger: 'blur' }],
        dateTime: [{ required: true, message: '请选择时间', trigger: 'blur' }],
        userId: [{ required: true, message: '请选择操作人', trigger: 'blur' }],
        landName: [{ required: true, message: '请选择地块', trigger: 'blur' }]
      },
      rulesCustom: {
        name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入类型编码', trigger: 'blur' }]
      },
      fType: 0,
      userList: [], // 用户列表
      baseInfoList: [] // 地块列表
    }
  },
  computed: {
  },
  created () {
    this.baseId = this.$store.getters.userInfo.baseId
    this.getData()
  },

  methods: {
    // 返回
    back () {
      this.$router.go(-1)
    },
    visibleChange (visible) {
      // 下拉框显示隐藏
      if (visible) {
        const ref = this.$refs.selectInput
        let popper = ref.$refs.popper
        if (popper.$el) popper = popper.$el
        // 判断是否有添加按钮
        if (!Array.from(popper.children).some(v => v.className === 'btn-box')) {
          const el = document.createElement('div')
          el.className = 'btn-box'
          el.innerHTML = `<a style="border-top:1px solid #CCCCCC;font-size:14px;padding: 0 20px;color: #606266;display:block;height: 34px;line-height: 34px;">
                            自定义
                          </a>`
          popper.appendChild(el)
          el.onclick = () => {
            this.dialogCustom = true
            this.$nextTick(() => {
              this.resetForm('ruleFormCustom')
            })
            // todo
          }
        }
      }
    },
    // 地块数据显示
    getAgriLand () {
      this.$refs.agriLand.getIdHas(this.addForm.landList)
    },
    // 获取地块信息
    getLandIds (landIds, landList) {
      this.$set(this.addForm, 'landList', landList)
      this.addForm.landIds = landIds
      this.addForm.landName = landList.map(item => { return item.landName }).toString()
      console.log(this.addForm.landName)
      this.$refs.ruleForm.validateField('landName')
    },
    // 地块删除
    deleteLand (index) {
      this.addForm.landList.splice(index, 1)
      this.addForm.landIds = ''
      this.addForm.landName = ''
      const landIds = []
      const landName = []
      this.addForm.landList.map(item => {
        landIds.push(item.landIds)
        landName.push(item.landName)
      })
      this.addForm.landIds = landIds.toString()
      this.addForm.landName = landName.toString()
    },
    // 关闭
    dialogBeforeClose () {
      this.dialogVisible = false
      this.addForm = this.$options.data().addForm
    },
    // 关闭
    dialogBeforeCustom () {
      this.dialogCustom = false
      this.formCustom = this.$options.data().formCustom
    },
    // 地块列表
    getBaseInfolist () {
      getBaseInfolistApi().then(res => {
        this.baseInfoList = res.data
      })
    },
    async getData (content, type) {
      // 农事类型
      this.fType = type
      this.getSysSonDictList('NS')
      this.getUserList()
      this.getBaseInfolist()
      this.dialogVisible = true
      this.$nextTick(async () => {
        this.resetForm('ruleForm')
        this.addForm.dateTime = []
      })
    },
    // 字典接口
    async getSysSonDictList (code) {
      const res = await getSysSonDictListApi(code)
      this.farmsList = res.data
    },
    // 用户list
    async getUserList () {
      const res = await getUserListApi(this.baseId)
      // console.log(res)
      this.userList = res.data
    },
    addBtn () {
      this.dialogVisible = !this.dialogVisible
    },
    // 子组件事件--添加农资
    farmsStockData (data) {
      console.log(data, '选中的农资')
      this.addForm.name = data.name
      this.addForm.agriDicId = data.id
      this.addForm.specifications = data.specifications
      this.addForm.type = data.typeCode
      this.inputShow = true
      this.dialogVisible = false
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = this.fType === 1
            ? await updateAgriplan({
              baseId: this.baseId,
              id: this.addForm.id,
              landIds: this.addForm.landIds,
              agriCode: this.addForm.agriCode,
              startTime: this.addForm.dateTime[0],
              endTime: this.addForm.dateTime[1],
              remark: this.addForm.remark,
              userId: this.addForm.userId
            })
            : await addAgriplantApi({
              baseId: this.baseId,
              landIds: this.addForm.landIds,
              agriCode: this.addForm.agriCode,
              startTime: this.addForm.dateTime[0],
              endTime: this.addForm.dateTime[1],
              remark: this.addForm.remark,
              userId: this.addForm.userId
            })
          this.$message.success(res.msg ? res.msg : '提交成功')
          this.back()
        } else {
          // this.$message.error('请正确填写')
          return false
        }
      })
    },
    submitFormCustom (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const res = await addDic({
            code: this.formCustom.code,
            name: this.formCustom.name,
            isParent: 0,
            parentCode: 'NS',
            parentId: 3
          })
          this.$message.success(res.msg ? res.msg : '提交成功')
          this.getSysSonDictList('NS')
          this.dialogBeforeCustom()
        } else {
          // this.$message.error('请正确填写')
          return false
        }
      })
    },
    // 操作人下拉事件
    onSelectChange (value) {
      const userInfo = this.userList.filter((item) => item.userName === value)
      // console.log(userInfo)
      this.addForm.participantsId = userInfo[0].userId
    },
    // 农资弹窗关闭
    handleClose (dome) {
      dome()
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].clearValidate()
      this.$refs[formName].resetFields()
    },
    // 编辑
    editForm () {
      if (this.missionDetail.id !== null) {
        // console.log(this.missionDetail, '农事')
        this.addForm.code = this.missionDetail.code
        this.addForm.participants = this.missionDetail.participants
        // this.addForm.area = this.missionDetail.area
        this.addForm.time = this.missionDetail.time
        this.addForm.way = this.missionDetail.way
        if (this.missionDetail.picture !== undefined) {
          this.addForm.picture = this.missionDetail.picture.split(',')
            .map((picture) => picture)
        }
        this.addForm.remark = this.missionDetail.remark
      }
    }
  }
}
</script>
<style scoped lang="scss">
.back {
  position: absolute;
  top: 5%;
  left: 5%;
}
.name {
  display: inline-block;
  ::v-deep .el-form-item__content {
    display: flex;
  }
  .addBtn {
    margin-left: .5208vw;
  }
}
.selectInput {
  width: 100%;
}
.require {
  color: red;
}
::v-deep .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  color: #00000000;
  margin-right: 0;
  display: none
}
::v-deep .el-dialog__body {
  padding: 30px 20px 15px 20px;
}
.textCenter {
  border-top: 1px solid #E5E5E5;
  text-align: center;
  padding-top: 15px;
}
.noneClose {
  background-color: #ffffff;
  border-color: #cccccc;
  color: #999
}
::v-deep .el-dialog__title {
  border-left: unset;
  padding: 0 0.5208vw;
  font-weight: 600;
}
.landContent {
  background: #FAFAFA;
  padding: 15px 10px;
  line-height: 1;
  width: 300px;
  .el-icon-error {
    position: absolute;
    color: #F76560;
    right: -5px;
    top: -5px;
    font-size: 15px;
  }
  .landContentT {
    font-weight: 500;
    font-size: 18px;
    color: #000000;
    span {
      font-size: 12px;
      padding: 2px 5px;
      margin-left: 5px;
    }
  }
  .landContentC {
    font-size: 12px;
    color: #666666;
    margin-top: 15px;
    span+span {
      margin-left: 35px;
    }
  }
}
.landFlex {
  display: flex;
  flex-wrap: wrap;
  >div {
    margin-right: 15px;
  }
  >div:nth-child(3n) {
    margin-right: 0;
  }
  .landContentBtn {

  }
}
</style>
<style>
/* .el-dialog__header {
  background: #002a52;
  text-align: center;
} */
</style>
